package com.xlongwei.todays.config;


import java.util.stream.Collectors;
import org.noear.snack.ONode;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import lombok.extern.slf4j.Slf4j;

/**
 * -Dsolon.logging.logger.com.xlongwei.accounts.config.LoggingRouterInterceptor=debug
 * 
 * @see 全局日志：https://solon.noear.org/article/625
 * @see 日志级别：https://solon.noear.org/article/family-solon-logging
 */
@Slf4j
@Component(index = -30)
public class LoggingRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain)
            throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("{} {}", ctx.method(), ctx.path());
            if (!ctx.paramMap().isEmpty()) {
                log.debug("params {}", ctx.paramMap().toValuesMap().entrySet().stream()
                        .map(entry -> entry.getKey() + "="
                                + entry.getValue().stream().collect(Collectors.joining(",")))
                        .collect(Collectors.joining("&")));
            }
            if (Utils.isNotBlank(ctx.bodyNew())) {
                log.debug("body {}", ctx.bodyNew());
            }
            long start = System.currentTimeMillis();
            chain.doIntercept(ctx, mainHandler);
            long timespan = System.currentTimeMillis() - start;
            log.debug("res({}) {}", timespan, ONode.load(ctx.result).toJson());
        } else {
            chain.doIntercept(ctx, mainHandler);
        }
    }
}
